const path = require('path')        // 导入nodejs的path模块
const webpack = require('webpack')  // 导入webpack

// 把ccs单独打包到文件里
const extractTextPlugin = require('extract-text-webpack-plugin')
// 自动生成html模板的处理
const htmlWebpackPlugin = require('html-webpack-plugin')

// 自动生成html模板处理的配置函数，获取html-webpack-plugin参数的方法
var getHtmlConfig = function (htmlName, title) {
  return {
    template: './src/view/' + htmlName + '.html',
    filename: 'view/' + htmlName + '.html',
    title: title,
    inject: true,
    hash: true,
    chunks: ['common', htmlName]
  }
}


// webpack config
const config = {
  entry: {
    'common': ['./src/page/common/index.js'],
    'index': ['./src/page/index/index.js'],
    'user-login': ['./src/page/user-login/index.js'],
    'user-register': ['./src/page/user-register/index.js'],
    'user-pass-reset': ['./src/page/user-pass-reset/index.js'],
    'user-pass-update': ['./src/page/user-pass-update/index.js'],
    'user-center': ['./src/page/user-center/index.js'],
    'user-center-update': ['./src/page/user-center-update/index.js'],
    'result': ['./src/page/result/index.js']
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist',
    filename: 'js/[name].js'
  },
  externals: {
    'jquery': 'window.jQuery'
  },
  resolve: {
    alias: {
      util:         __dirname + '/src/util',
      page:         __dirname + '/src/page',
      service:      __dirname + '/src/service',
      image:        __dirname + '/src/img',
      node_modules: __dirname + '/node_modules'
    }
  },
  plugins: [
    // webpack把独立模块提取 --> 通用模块js/base.js
    new webpack.optimize.CommonsChunkPlugin({
      name: 'common',
      filename: 'js/base.js'
    }),
    // 把ccs单独打包到文件里
    new extractTextPlugin('css/[name].css'),

    // html模板的处理
    new htmlWebpackPlugin(getHtmlConfig('index', '首页')),
    new htmlWebpackPlugin(getHtmlConfig('user-login', '用户登录')),
    new htmlWebpackPlugin(getHtmlConfig('user-register', '用户注册')),
    new htmlWebpackPlugin(getHtmlConfig('user-pass-reset', '找回密码')),
    new htmlWebpackPlugin(getHtmlConfig('user-pass-update', '修改密码')),
    new htmlWebpackPlugin(getHtmlConfig('user-center', '个人中心')),
    new htmlWebpackPlugin(getHtmlConfig('user-center-update', '修改个人信息')),
    new htmlWebpackPlugin(getHtmlConfig('result', '操作结果')),
  ],
  module: {
    loaders: [
      {
        test: /\.string$/i,
        loader: 'html-loader'
      },
      {
        test: /\.(css|scss)$/,
        loader: extractTextPlugin.extract('style-loader', 'css-loader!sass-loader')
      },
      {
        test: /\.(gif|png|jpg|woff|svg|eot|ttf)\??.*$/i,
        loader: 'url-loader?limit=100&name=resource/[name].[ext]'
      }
    ]
  }
}

// 环境变量配置，本地开发或线上环境，dev / online
const WEBPACK_ENV = process.env.WEBPACK_ENV || 'dev'
if (WEBPACK_ENV === 'dev') {
  config.entry.common.push('webpack-dev-server/client?http://localhost:8088/')
}

module.exports = config